//
//  ZGLPlayMapVC.m
//  Faker
//
//  Created by dllo on 15/11/9.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLPlayMapVC.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "LineDashPolyline.h"

#pragma mark 1 - 声明属性 签协议

@interface ZGLPlayMapVC ()<MAMapViewDelegate, AMapSearchDelegate>
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) NSArray *polyLines;
@property (nonatomic, assign) CGFloat meter;//距离
@property (nonatomic, assign) CGFloat time;//时间
@property (nonatomic, assign) CGFloat fare;//打车费
@property (nonatomic, assign) CGFloat yLatitude;//定位纬度
@property (nonatomic, assign) CGFloat xLongitude;//定位经度
@property (nonatomic, copy) NSString *str;//目的地
@property (nonatomic, copy) NSString *cityStr;//大头针信息显示
@property (nonatomic, strong)  UIButton *locationButton;//定位按钮
@property (nonatomic, strong) MAPointAnnotation *point2;//第二个大头针
@property (nonatomic) MAUserTrackingMode userTrackingMode;
//@property (nonatomic, copy) NSString *depart;//出发地
@property (nonatomic, strong) UILabel *distanceLabel;//距离
@property (nonatomic, strong) UILabel *costLabel;//价钱
@property (nonatomic, strong) UILabel *totalTimeLabel;//用时
@property (nonatomic, assign) CGFloat x;//经度
@property (nonatomic, assign) CGFloat y;//纬度
@property (nonatomic, strong) UIView *backGroundView;//显示背景view
@property (nonatomic, strong) UILabel *closeLabel;//关闭


@end

@implementation ZGLPlayMapVC
/* 初始化mapview */
- (instancetype)init {
    self = [super init];
    if (self) {
        /* 创建MAMap */
        self.mapView = [[MAMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.view addSubview:self.mapView];
        self.mapView.delegate = self;
        
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark 2 - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zaihufanhui"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItem)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    /* 设置key值 */
    [MAMapServices sharedServices].apiKey = @"e651ab4e701605c42d8f23599b5292ee";
    /* POI搜索 */
    [AMapSearchServices sharedServices].apiKey = @"e651ab4e701605c42d8f23599b5292ee";
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    /* 设置指南针 */
    self.mapView.showsCompass = YES; //默认为YES
    self.mapView.compassOrigin = CGPointMake(330 * ScaleX, 70 * ScaleX);
    /* 比例尺 */
    self.mapView.showsScale = YES;  //默认为YES
    self.mapView.scaleOrigin = CGPointMake(20 * ScaleX, 100 * ScaleX);
    /* 地图手势操作 */
    self.mapView.zoomEnabled = YES; //是否支持缩放 默认为YES
    self.mapView.zoomLevel = 10; //缩放比例  1--20
    /* 地图平移 */
    self.mapView.scrollEnabled = YES;
    /* 定位 */
    self.mapView.showsUserLocation = YES;
    // Do any additional setup after loading the view.
}
#pragma mark 3 - 属性set方法重写 返回键
//返回键点击事件
-(void)leftBarButtonItem {
    [self.navigationController popViewControllerAnimated:YES];
}
//属性set方法重写
-(void)setLocation:(AMapGeoPoint *)location {
    if (_location != location) {
        _location = location;
    }
    
    self.mapView.centerCoordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude);
    MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
    point.coordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude);
    [self.mapView addAnnotation:point];
    //值过来创建
    [self createCHAXUN];
}
#pragma mark 4 - 实现正向地理编码的回调函数
//获取目的地的经纬度
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response {
    if(response.geocodes.count == 0) {
        return;
    }
    UITextField *text = (UITextField *)[self.view viewWithTag:1];
    if (text.tag == 1) {
        
        //处理搜索结果
        for (AMapGeocode *p in response.geocodes) {
            self.x = p.location.latitude;
            self.y = p.location.longitude;
        }
        //显示路线
        [self create];
        
    }
}
#pragma mark 5 - 输入目的地视图创建
- (void)createCHAXUN {
    UILabel *nameLabel  = [[UILabel alloc] initWithFrame:CGRectMake(20, 64, 300 * ScaleX, 34)];
    nameLabel.text = @" 目的地:";
    nameLabel.numberOfLines = 3;
    nameLabel.backgroundColor = [UIColor whiteColor];
    nameLabel.textAlignment = 0;
    [self.view addSubview:nameLabel];
    
    UITextField *mudi = [[UITextField alloc] initWithFrame:CGRectMake(90 * ScaleX, 70, 150 * ScaleX, 25)];
    [self.view addSubview:mudi];
    mudi.placeholder = @"请输入目的地";
    mudi.layer.cornerRadius = 5;
    mudi.borderStyle = 3;
    mudi.layer.masksToBounds = YES;
    mudi.tag = 1;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"开始导航" forState:UIControlStateNormal];
    button.frame = CGRectMake(245 * ScaleX, 70, 60, 30);
    [self.view addSubview:button];
    [button addTarget:self action:@selector(button) forControlEvents:UIControlEventTouchUpInside];
}
//开始导航点击事件
- (void)button {
    UITextField *text = (UITextField *)[self.view viewWithTag:1];
    self.str = text.text;
    [self createCat:text.text];
    //输入提示搜索
    AMapInputTipsSearchRequest *inPutTip = [[AMapInputTipsSearchRequest alloc] init];
    inPutTip.keywords = self.str;
    inPutTip.city = self.city;
    [self.search AMapInputTipsSearch:inPutTip];
}
#pragma mark 6 - 点击开始导航后，详细信息
- (void)createInfoView {
    self.backGroundView = [UIView new];
    [self.view addSubview:self.backGroundView];
    self.backGroundView.frame = CGRectMake(Width / 2 + 10 * ScaleX + (Width / 2 - 20 * ScaleX) / 2, 135 * ScaleX + (Height / 2 - 120 * ScaleX) / 2, 0, 0);
    self.backGroundView.backgroundColor = [UIColor whiteColor];
    self.distanceLabel = [UILabel new];
    [self.backGroundView addSubview:self.distanceLabel];
    self.distanceLabel.numberOfLines = 0;
    self.costLabel = [UILabel new];
    [self.backGroundView addSubview:self.costLabel];
    self.costLabel.numberOfLines = 0;
    self.totalTimeLabel = [UILabel new];
    [self.backGroundView addSubview:self.totalTimeLabel];
    self.totalTimeLabel.numberOfLines = 0;
    self.closeLabel = [UILabel new];
    [self.backGroundView addSubview:self.closeLabel];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backGroundView.frame = CGRectMake(Width / 2 + 10 * ScaleX, 135 * ScaleX, Width / 2 - 20 * ScaleX, Height / 2 - 180 * ScaleX);
    } completion:^(BOOL finished) {
        [self setSubViewsFrame];
    }];
}
#pragma mark 6 ** 详细信息铺界面
- (void)setSubViewsFrame {
    [UIView animateWithDuration:0.3 animations:^{
        self.distanceLabel.frame = CGRectMake(10 * ScaleX, 10 * ScaleX, self.backGroundView.frame.size.width - 20, self.backGroundView.frame.size.height / 3 - 10 * ScaleX);
        self.costLabel.frame = CGRectMake(10 * ScaleX, self.backGroundView.frame.size.height / 4 + 10 * ScaleX, self.backGroundView.frame.size.width - 20 * ScaleX, self.backGroundView.frame.size.height / 3 - 10 * ScaleX);
        self.totalTimeLabel.frame = CGRectMake(10 * ScaleX, self.backGroundView.frame.size.height * 2 / 4 + 10 * ScaleX, self.backGroundView.frame.size.width - 20 * ScaleX, self.backGroundView.frame.size.height / 3 - 10 * ScaleX);
        self.closeLabel.frame = CGRectMake(self.backGroundView.frame.size.width / 2 - 20 * ScaleX, self.backGroundView.frame.size.height * 3 / 4 + 10 * ScaleX,  self.backGroundView.frame.size.width - 20 * ScaleX, 20 * ScaleX);
        self.closeLabel.text = @"关闭";
        self.closeLabel.textColor = [UIColor redColor];
        self.closeLabel.font = [UIFont systemFontOfSize:14];
        
    }];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[touches allObjects] lastObject];
    if (touch.view == self.backGroundView) {
        [UIView animateWithDuration:0.3 animations:^{
            self.backGroundView.alpha = 0;
        } completion:^(BOOL finished) {
            [self.costLabel removeFromSuperview];
            [self.totalTimeLabel removeFromSuperview];
            [self.distanceLabel removeFromSuperview];
            [self.backGroundView removeFromSuperview];
            
            self.costLabel = nil;
            self.totalTimeLabel = nil;
            self.distanceLabel = nil;
            self.backGroundView = nil;
        }];
    }
}
- (void)createCat:(NSString *)str {
    
    //正向地理编码
    AMapGeocodeSearchRequest *geoRequest = [[AMapGeocodeSearchRequest alloc] init];
    geoRequest.address = str;
    //地址编码查询接口
    [self.search AMapGeocodeSearch:geoRequest];
    UITextField *text = (UITextField *)[self.view viewWithTag:1];
    [text resignFirstResponder];
    UITextField *departure = (UITextField *)[self.view viewWithTag:10];
    [departure resignFirstResponder];
}
#pragma mark - 经纬度 划线
- (void)create {
    //路径规划查询
    //驾车为例
    //构造AMapDrivingRouteSearchRequest对象, 配置查询参数  AMapWalkingRouteSearchRequest 步行路径规划AMapTransitRouteSearchRequest 公交路径规划
    AMapDrivingRouteSearchRequest *drive = [[AMapDrivingRouteSearchRequest alloc] init];
    NSLog(@"hhhhhh");
    drive.origin = [AMapGeoPoint locationWithLatitude:self.location.latitude longitude:self.location.longitude];
    drive.destination = [AMapGeoPoint locationWithLatitude:self.x longitude:self.y];
    drive.requireExtension = YES; //是否返回扩展信息，默认NO
    [self.search AMapDrivingRouteSearch:drive];
    if (self.backGroundView == nil) {
        [self createInfoView];
        
    } else {
        
    }
}

/* 打车 行程计算 */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    //打车费
    self.fare = response.route.taxiCost;
    AMapPath *path = response.route.paths[0];
    //距离
    self.meter = (long)path.distance;
    NSLog(@"策略:%@", path.strategy);
    //时间分钟
    self.time = path.duration / 60.f;
    
    [self.mapView removeOverlays:self.polyLines];
    self.polyLines = nil;
    self.distanceLabel.text = [NSString stringWithFormat:@"距离:%.2lf米", self.meter];
    self.costLabel.text = [NSString stringWithFormat:@"打车费:%.2lf元",self.fare];
    self.totalTimeLabel.text = [NSString stringWithFormat:@"预计耗时:%.2lf分钟",self.time];
    //只显示第一条
    self.polyLines = [self polylinesForPath:response.route.paths[0]];
    [self.mapView addOverlays:self.polyLines];
    
    //设置显示大头针位置
    self.point2.coordinate = CLLocationCoordinate2DMake(self.x, self.y);
    self.point2.title = self.cityStr;
    self.point2.subtitle = self.str;
    [self.mapView addAnnotation:self.point2];
}

//MAOverlayView 函数回调
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay {
    
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineView *polyLineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        polyLineView.lineWidth = 5;
        polyLineView.strokeColor = [UIColor magentaColor];
        
        return polyLineView;
    }
    return nil;
}
- (NSArray *)polylinesForPath:(AMapPath *)path
{
    if (path == nil || path.steps.count == 0)
    {
        return nil;
    }
    
    NSMutableArray *polylines = [NSMutableArray array];
    
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL *stop) {
        
        MAPolyline *stepPolyline = [self polylineForStep:step];
        
        if (stepPolyline != nil)
        {
            [polylines addObject:stepPolyline];
            
            if (idx > 0 )
            {
                [self replenishPolylinesForPathWith:stepPolyline lastPolyline:[self polylineForStep:[path.steps objectAtIndex:idx-1]]  Polylines:polylines];
            }
        }
    }];
    
    return polylines;
}
//返回多个路段的基本信息
- (MAPolyline *)polylineForStep:(AMapStep *)step
{
    if (step == nil)
    {
        return nil;
    }
    
    return [self polylineForCoordinateString:step.polyline];
}
- (void)replenishPolylinesForPathWith:(MAPolyline *)stepPolyline lastPolyline:(MAPolyline *)lastPolyline Polylines:(NSMutableArray *)polylines
{
    CLLocationCoordinate2D startCoor ;
    CLLocationCoordinate2D endCoor;
    
    //将内部的坐标点数据转化为经纬度坐标并拷贝到coords内存中
    [stepPolyline getCoordinates:&endCoor range:NSMakeRange(0, 1)];
    [lastPolyline getCoordinates:&startCoor range:NSMakeRange(lastPolyline.pointCount -1, 1)];
    
    
    if ((endCoor.latitude != startCoor.latitude || endCoor.longitude != startCoor.longitude ))
    {
        CLLocationCoordinate2D points[2];
        points[0] = startCoor;
        points[1] = endCoor;
        
        //根据经纬度坐标数据生成多段线
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:points count:2];
        LineDashPolyline *dathPolyline = [[LineDashPolyline alloc] initWithPolyline:polyline];
        dathPolyline.polyline = polyline;
        [polylines addObject:dathPolyline];
    }
}
//返回多段线
- (MAPolyline *)polylineForCoordinateString:(NSString *)coordinateString
{
    if (coordinateString.length == 0)
    {
        return nil;
    }
    
    NSUInteger count = 0;
    
    CLLocationCoordinate2D *coordinates = [self coordinatesForString:coordinateString
                                                     coordinateCount:&count
                                                          parseToken:@";"];
    
    //根据经纬度坐标生成多段线
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
    
    free(coordinates), coordinates = NULL;
    
    return polyline;
}
#pragma mark - 路径规划函数回调
//字符串解析
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount parseToken:(NSString *)token {
    if (string == nil) {
        return NULL;
    }
    if (token == nil) {
        token = @",";
    }
    NSString *str = @"";
    if (![token isEqualToString:@","]) {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    else {
        str = [NSString stringWithString:string];
    }
    //将分割的字符串存放到数组中
    NSArray *components = [str componentsSeparatedByString:@","];
    
    NSLog(@"%@", components);
    
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL) {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++) {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    return coordinates;
}
#pragma mark - 定位 即时更新位置
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation {
    if(updatingLocation) {
        //取出当前位置的坐标
        CLLocation *newLocation = userLocation.location;
        //判断时间
        NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
        if (locationAge > 5.0) {
            return;
        }
        //判断水平精度是否有效
        if (newLocation.horizontalAccuracy < 0) {
            return;
        }
        //根据业务需求，进行水平精度判断，获取所需位置信息（100可改为业务所需值）
        if(newLocation.horizontalAccuracy < 100){
            //获取定位位置的经纬度
            
            CLLocationCoordinate2D myCoordinate = [newLocation coordinate];
            // 纬度
            CGFloat latitude = myCoordinate.latitude;
            // 经度
            CGFloat longitude = myCoordinate.longitude;
            NSLog(@"%f%f", latitude, longitude);
            // 显示在View中心位置
            
            self.mapView.centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
            
            //停止定位
            _mapView.showsUserLocation = NO;
            
        }
    }
}



//#import <MAMapKit/MAMapKit.h>
//#import <AMapSearchKit/AMapSearchKit.h>
//
//
//@interface ZGLPlayMapVC ()<MAMapViewDelegate, AMapSearchDelegate>
//@property (nonatomic, strong) MAMapView *mapView;
//@property (nonatomic, strong) AMapSearchAPI *search;
//
//
//@end
//
//@implementation ZGLPlayMapVC
//#pragma mark - 设置大头针
//- (instancetype)init
//{
//    self = [super init];
//    if (self) {
//        /* 创建MAMap */
//        self.mapView = [[MAMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//        [self.view addSubview:self.mapView];
//        self.mapView.delegate = self;
//        
//    }
//    return self;
//}
//-(void)viewWillAppear:(BOOL)animated {
//    self.tabBarController.tabBar.hidden = YES;
//}
//-(void)viewWillDisappear:(BOOL)animated {
//    self.tabBarController.tabBar.hidden = NO;
//}
//- (void)viewDidLoad {
//    [super viewDidLoad];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zaihufanhui"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItem)];
//    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
//    /* 设置key值 */
//    [MAMapServices sharedServices].apiKey = @"f47e32d3102eda1c75f67e13afe18c11";
//    /* POI搜索 */
//    [AMapSearchServices sharedServices].apiKey = @"f47e32d3102eda1c75f67e13afe18c11";
//    self.search = [[AMapSearchAPI alloc] init];
//    self.search.delegate = self;
//    
//    /* 创建MAMap */
//    self.mapView = [[MAMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    [self.view addSubview:self.mapView];
//    self.mapView.delegate = self;
//    
//    /* 设置指南针 */
//    self.mapView.showsCompass = YES; //默认为YES
//    self.mapView.compassOrigin = CGPointMake(330, 70);
//    
//    /* 比例尺 */
//    self.mapView.showsScale = YES;  //默认为YES
//    self.mapView.scaleOrigin = CGPointMake(20, 70);
//    
//    /* 地图手势操作 */
//    self.mapView.zoomEnabled = YES; //是否支持缩放 默认为YES
//    self.mapView.zoomLevel = 10; //缩放比例  1--20
//    
//    /* 地图平移 */
//    self.mapView.scrollEnabled = YES;
//    /* 定位 */
//    self.mapView.showsUserLocation = YES;
//    // Do any additional setup after loading the view.
//}
//-(void)leftBarButtonItem {
//    [self.navigationController popViewControllerAnimated:YES];
//}
//
//-(void)setLocation:(AMapGeoPoint *)location {
//    if (_location != location) {
//        _location = location;
//    }
//    self.mapView.centerCoordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude);
//    MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
//    point.coordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude);
//    [self.mapView addAnnotation:point];
//    
//}
//

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
